package com.jianganming.netty.rpc.registry;

import com.jianganming.netty.rpc.protocol.InvokerProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class RegistryHandler extends ChannelInboundHandlerAdapter {
    private ConcurrentHashMap<String, Object> registryMap;

    public RegistryHandler(ConcurrentHashMap<String, Object> registryMap){
        this.registryMap = registryMap;
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        InvokerProtocol request = (InvokerProtocol) msg;
        if (registryMap.containsKey(request.getClassName())) {
            Object clazz = registryMap.get(request.getClassName());
            Method method = clazz.getClass().getMethod(request.getMethodName(), request.getParames());
            Object result = method.invoke(clazz, request.getValues());
            ctx.write(result);
            ctx.flush();
            ctx.close();
        }
    }
}
